package main

import (
	"fmt"
	"net"
	"bufio"
	"os"
	"syscall"
)

func checkError(err error) {
	if err != nil {
		fmt.Printf("Error: %s\n", err.Error())
		os.Exit(1)
	}
}

func writeUnix(listener *net.UnixConn, dstAddr *net.UnixAddr) {
	for {
		bio := bufio.NewReader(os.Stdin)
		buf, _, _ := bio.ReadLine()
		_, err := listener.WriteToUnix(buf, dstAddr)
		checkError(err)
	}
}

func readUnix(listener *net.UnixConn) {
	for {
		buf := make([]byte, 1400)
		size, remote, err := listener.ReadFromUnix(buf)
		checkError(err)
		fmt.Println("recv: ", string(buf[:size]), " from ", remote.String())
	}
}

func runUnix() {
	addr, err := net.ResolveUnixAddr("unixgram", "/tmp/gsocket")
	checkError(err)
	syscall.Unlink("/tmp/gsocket")
	listener, err := net.ListenUnixgram("unixgram", addr)
	defer listener.Close()
	checkError(err)

	dstAddr, err := net.ResolveUnixAddr("unixgram", "/tmp/csocket")

	go readUnix(listener)
	go writeUnix(listener, dstAddr)
	
	select {}
}

func main() {
	runUnix()
}
